import { userService } from "@/services";
import { getField, updateField } from "vuex-map-fields";
import { timeout } from "q";
const user = {
  username: "Admin",
  user: {
    follower: 0,
    following: 0,
    status: "ONLINE",
    wachers: 0,
    privacy: {
      name: "Admin",
      birthday: undefined
    }
  }
};
const initialState = { edit: false, status: {}, user: user };

export const authentication = {
  namespaced: true,
  state: initialState,
  getters: {
    getField
  },
  actions: {
    login({ dispatch, commit }, { username, password }) {
      commit("loginRequest", { username });
      userService.login(username, password).then(
        user => {
          commit("loginSuccess", user);
          window.location.assign(`http://localhost:8080/`);
        },
        error => {
          commit("loginFailure", error);
          dispatch("alert/error", error, { root: true });
        }
      );
    },
    update({ dispatch, commit }, playload) {
      userService.update(playload).then(
        response => {
          console.log("成功成功了");
        },
        error => {
          dispatch("alert/error", error, { root: true });
        }
      );
    },
    current({ dispatch, commit }) {
      userService.getCurrent().then(
        user => {
          console.log("收到的user");
          console.log(user);
          commit("currentSuccess", user);
        },
        error => {
          commit("loginFailure", error);
          dispatch("alert/error", error, { root: true });
        }
      );
    },
    logout({ commit }) {
      userService.logout();
      commit("logout");
    },
    register({ dispatch, commit }, user) {
      userService.register(user).then(user => {
        alert("注册成功,将跳转到到了页面");
        setTimeout(function() {
          window.location.assign(`http://localhost:8080/sign/#/`);
        }, 1000);
        //window.location.assign(`http://localhost:8080/sign/#/`);
      });
    },
    edit({ commit }) {
      commit("edit");
    }
  },
  mutations: {
    updateField,
    edit(state) {
      if (state.edit) {
        state.edit = false;
      } else {
        state.edit = true;
      }
    },
    loginRequest(state, user) {
      state.status = { loggingIn: true };
      state.user = user;
    },
    loginSuccess(state, token) {
      state.status = { loggedIn: true };
      state.token = token;
    },
    currentSuccess(state, user) {
      state.status = { loggedIn: true };
      state.user = user;
    },
    loginFailure(state) {
      state.status = {};
      state.user = null;
    },
    logout(state) {
      state.status = {};
      state.user = null;
    }
  }
};
